package pe.com.rimac.portal.util.url.impl;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.ibm.portal.portlet.service.PortletService;
import com.ibm.portal.portlet.service.PortletServiceHome;
import com.ibm.portal.portlet.service.PortletServiceUnavailableException;
import com.ibm.portal.portlet.service.model.ContentModelProvider;
import com.ibm.portal.portlet.service.model.PortletModelProvider;
import com.ibm.portal.state.service.PortletStateManagerService;

public class ServiceLocator 
{
    private static ServiceLocator instance = new ServiceLocator();
    
    public static ServiceLocator getInstance()
    {
        return instance;
    }
    
    private Context ctx;
    
    private ServiceLocator()
    {
        try
        {
            ctx = new InitialContext();
        }
        catch (NamingException e)
        {
            throw new ServiceLocatorException("Could not initialise Context", e);
        }   
    }
    
    private PortletServiceHome lookupPortletServiceHome(String jndi)
    {
        try
        {
            return (PortletServiceHome) ctx.lookup(jndi);
        }
        catch (NamingException e)
        {
            throw new ServiceLocatorException("Could not find jndi '"+jndi+"'", e);
        }
    }
    
    private PortletService getPortletService(String jndi, Class clazz)
    {
        try
        {
           PortletServiceHome psh = lookupPortletServiceHome(jndi);
           if (psh == null)
           {
               throw new ServiceLocatorException("PortServiceHome was null");  
           }
           return psh.getPortletService(clazz);
        }
        catch (PortletServiceUnavailableException e)
        {
            throw new ServiceLocatorException("Unable to get "+clazz.getName(), e);
        }
    }
    
    public PortletStateManagerService getPortletStateManagerService()
    {
        return (PortletStateManagerService) getPortletService("portletservice/com.ibm.portal.state.service.PortletStateManagerService", PortletStateManagerService.class);
    }
    
    public PortletModelProvider getPortletModelProvider()
    {
        return (PortletModelProvider) getPortletService("portletservice/com.ibm.portal.portlet.service.model.PortletModelProvider", PortletModelProvider.class);
    }
    
    public ContentModelProvider getContentModelProvider()
    {
        return (ContentModelProvider) getPortletService("portletservice/com.ibm.portal.portlet.service.model.ContentModelProvider", ContentModelProvider.class);
    }
}